#include "myfile.h"
#include <stdlib.h>

#ifdef USE_STDIO

MYFile myopen(char *fname, int mode)
{
  char *m = "r";

  switch(mode)
  {
    case MRead: m = "r"; break;
    case MReadWrite: m = "r+"; break;
    case MWriteCreate: m = "w"; break;
    case MReadWriteCreate: m = "w+"; break;
  }

  return fopen(fname, m);
}

int myread(MYFile file, void *buf, int len)
{
  int result = fread(buf, 1, len, file);

  if(!result)
  {
    if(ferror(file)) return -1;
  }

  return result;
}

int mywrite(MYFile file, void *buf, int len)
{
  int result = fwrite(buf, 1, len, file);

  if(!result)
  {
    if(ferror(file)) return -1;
  }

  return result;
}

#else

#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

MYFile myopen(char *fname, int mode)
{
  int m = O_RDONLY;

  switch(mode)
  {
    case MRead: m = O_RDONLY; break;
    case MReadWrite: m = O_RDWR; break;
    case MWriteCreate: m = O_WRONLY|O_CREAT|O_TRUNC; break;
    case MReadWriteCreate: m = O_RDWR|O_CREAT|O_TRUNC; break;
  }

  return open(fname, m);
}

#define BUF_SIZE 1024
int myfprintf(MYFile file, char *format, ...)
{
  char buf[BUF_SIZE];
  char *printBuf = buf;
  va_list a_list;

  va_start(a_list, format);
  int len = vsnprintf(buf,BUF_SIZE,format,a_list);
  va_end(a_list);

  if(len >= BUF_SIZE)
  {
    printBuf = (char *)malloc(sizeof(char)*(len+1));
    if(printBuf)
    {
      va_start(a_list, format);
      vsnprintf(printBuf,BUF_SIZE,format,a_list);
      va_end(a_list);
    }
  }

  if(printBuf)
  {
    int result = writeFile(file,printBuf,len);
    if(printBuf!=buf) free(printBuf);
    return result;
  }

  return 0;
}

#endif

